<?php
namespace ShenerCloud\Data\Model;

use ShenerCloud\Data\Exception\RequestException;

class Token
{
    public $access_token = '';
    public $refresh_token = "";
    public $expire_in = 0;
    private $access_file = 'access_token';
    
    const SUCCESS_CODE=100;
    
    public function __construct(Parameter $parameter)
    {
        $this->access_file = $parameter->path.'access_token';
        $params = '';
        if (file_exists($this->access_file))
            $params = file_get_contents($this->access_file);
        if (!empty($params)){
            $params = json_encode($params,TRUE);
            $this->access_token = isset($params['access_token'])?$params['access_token']:'';
            $this->refresh_token = isset($params['refresh_token'])?$params['refresh_token']:'';
            $this->expire_in = isset($params['expire_in'])?$params['expire_in']:0;
        }
    }
    
    /***
     * 检查Token是否过期
     * @return boolean
     */
    public function checkExpire()
    {
        if ($this->expire_in >0 && $this->expire_in > time())
            return true;
        return false;
    }
    
    /***
     * 检查是否需要刷新Token
     * @return boolean
     */
    public function checkRefreshToken()
    {
        if ($this->expire_in - time() <= 300 && $this->expire_in - time() > 0)
            return true;
        return false;
    }
    
    public function parseRequest(array $params)
    {
        if (isset($params['Code']) && $params['Code'] == self::SUCCESS_CODE
            && isset($params['Token'])){
            $this->access_token = isset($params['Token']['Token'])?$params['Token']['Token']:'';
            $this->refresh_token = isset($params['Token']['Refresh_token'])?$params['Token']['Refresh_token']:'';
            $this->expire_in = isset($params['Token']['Expire_in'])?$params['Token']['Expire_in']:0;
            
            //写到文件里面去
            $content = json_encode([
                'access_token'=>$this->access_token,
                'refresh_token'=>$this->refresh_token,
                'expire_in'=>$this->expire_in
            ]);
            $fp = fopen($this->access_file, "w");
            fwrite($fp, $content,strlen($content));
            fclose($fp);
        }
        if (isset($params['Code']) && isset($params['Error']))
            throw new RequestException($params['Code'].':'.$params['Error']);
        return false;
    }
}